package com.jml.netty.marshing;

import com.jml.io.utils.GzipUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.File;
import java.io.FileInputStream;

public class Client {

	public static void main(String[] args) throws Exception {
		
		EventLoopGroup workgroup = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(workgroup)
				//客户端使用的channel
		.channel(NioSocketChannel.class)
		.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel sc) throws Exception {

				sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
				sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
				sc.pipeline().addLast(new ClientHandler());
			}
		});
		//future表示异步的获取通道
		ChannelFuture cf = bootstrap.connect("127.0.0.1", 8765).sync();

		Channel channel = cf.channel();
		for (int i = 0; i < 5; i++) {
			String path = System.getProperty("user.dir")+ File.separatorChar+"sources" + File.separatorChar+"006.jpg";
			File file = new File(path);
			FileInputStream in = new FileInputStream(file);
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();

			Req req = new Req();
			req.setId(i+"");
			req.setName("pro"+i);
			req.setRequestMessage("数据信息"+i);
			req.setAttachment(GzipUtils.gzip(data));

			channel.writeAndFlush(req);
		}
		//Unpooled.copiedBuffer("777".getBytes());  返回的是缓冲字节
		//sync表示异步，异步释放连接
		channel.closeFuture().sync();
		workgroup.shutdownGracefully();
		
	}
}
